package com.start.client.app.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.start.client.app.entity.ClientAppVersionEntity;
import com.start.client.app.entity.ClientDownRecordEntity;
import com.start.client.app.enums.StartAppClientVersionType;
import com.start.client.app.mappers.ClientAppVersionMapper;
import com.start.client.app.service.ClientAppVersionService;
import com.start.client.app.service.ClientDownRecordService;
import com.start.client.app.vo.AppVersionResult;
import com.start.client.app.vo.ClientClientAppInfo;
import com.start.common.exceptions.StartBusException;
import com.start.common.tools.IPTools;
import com.start.common.tools.SpringContextTools;
import com.start.common.tools.StartEnumTools;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class ClientAppVersionServiceImpl extends ServiceImpl<ClientAppVersionMapper, ClientAppVersionEntity> implements ClientAppVersionService {
    @Autowired
    private ClientDownRecordService clientDownRecordService;

    /**
     * app 检查更新
     *
     * @param appInfo
     * @return
     */
    @Override
    public AppVersionResult checkAppUpdate2(ClientClientAppInfo appInfo) {
        if (appInfo == null) {
            throw new StartBusException("客户端信息不能为空");
        }
        if (StringUtils.isEmpty(appInfo.getPlatformType())) {
            throw new StartBusException("客户端类型不能为空");
        }
        if (StringUtils.isEmpty(appInfo.getAppId())) {
            throw new StartBusException("APPID不能为空");
        }
        StartAppClientVersionType appVersionType;

        appVersionType = StartEnumTools.findEnumByValue(StartAppClientVersionType.class, appInfo.getAppVersionType());
        if (appVersionType == null) {
            appVersionType = StartAppClientVersionType.PROD;
        }
        appInfo.setAppVersionType(appVersionType.getValue());
        ClientAppVersionEntity entity = getBaseMapper().checkAppUpdate(appInfo);
        if (entity == null) throw new StartBusException("未知APPID无法更新");
        if (appInfo.getVersionCode() >= entity.getAppVersionCode()) {
            return null;
        }
        if (entity.getAppUpdateType() == 1 && appInfo.getVersionCode() < entity.getMinimumFullVersionCode()) {
            entity = this.getOneByAppMangerIdAndVersionCode(entity.getAppManagerId(), entity.getMinimumFullVersionCode(), appVersionType);
            if (entity == null) return null;
        }
        String clientPlatform = appInfo.getPlatformType().toLowerCase();
        String urlConfig = null;
        switch (clientPlatform) {
            case "android":
                urlConfig = entity.getPlatformAndroid();
                break;
            case "ios":
                urlConfig = entity.getPlatformIos();
                break;
        }
        if (StringUtils.isEmpty(urlConfig)) {
            return null;
        }
        JSONArray jsonArray = JSON.parseArray(urlConfig);
        if (jsonArray.size() < 1) return null;
        final JSONObject jsonObject = jsonArray.getJSONObject(0);
        String url = jsonObject.containsKey("value") ? jsonObject.getString("value") : null;
        if (StringUtils.isEmpty(url)) return null;
        AppVersionResult result = AppVersionResult.appVersionToResult(entity, url, appInfo.getAppId());
        String ip = IPTools.getFullIpAddr(SpringContextTools.getHttpServletRequest());
        ClientDownRecordEntity downRecord = ClientDownRecordEntity.create(entity, clientPlatform, ip);
        clientDownRecordService.save(downRecord);
        return result;
    }

    @Override
    public ClientAppVersionEntity getOneByAppMangerIdAndVersionCode(String appManagerId, Integer versionCode, StartAppClientVersionType versionType) {
        LambdaQueryWrapper<ClientAppVersionEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClientAppVersionEntity::getAppManagerId, appManagerId);
        wrapper.eq(ClientAppVersionEntity::getAppVersionCode, versionCode);
        if (versionType != null) {
            wrapper.eq(ClientAppVersionEntity::getVersionType, versionType.getValue());
        }
        return getOne(wrapper, false);
    }

    @Override
    public ClientAppVersionEntity getMaxOneByFullVersion(String appManagerId, StartAppClientVersionType versionType) {
        LambdaQueryWrapper<ClientAppVersionEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClientAppVersionEntity::getAppManagerId, appManagerId);
        wrapper.eq(ClientAppVersionEntity::getAppUpdateType, 0);
        wrapper.eq(ClientAppVersionEntity::getVersionType, versionType.getValue());
        wrapper.orderByDesc(ClientAppVersionEntity::getAppVersionCode);
        wrapper.last(" LIMIT 1");
        return getOne(wrapper);
    }

    @Override
    public List<ClientAppVersionEntity> listFullVersionByAppManagerId(String appManagerId) {
        LambdaQueryWrapper<ClientAppVersionEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ClientAppVersionEntity::getAppManagerId, appManagerId);
        wrapper.eq(ClientAppVersionEntity::getAppUpdateType, 0);
        wrapper.orderByDesc(ClientAppVersionEntity::getAppVersionCode);
        return list(wrapper);
    }
}
